package org.gap.jseed;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.gap.jseed.injection.annotation.Inject;

public class MethodServiceInjector {

	public void inject(ServiceStoreContainer store, Object instance) {
		Method[] methods = instance.getClass().getMethods();
		for (Method each : methods) {
			each.setAccessible(true);
			if (hasInjectAnnotation(each)) {
				injectService(store, instance, each);
			}
		}
	}

	private boolean hasInjectAnnotation(Method method) {
		return method.getAnnotation(Inject.class) != null;
	}

	private void injectService(ServiceStoreContainer store, Object instance, Method each) {
		try {
			each.invoke(instance, store.get(each.getParameterTypes()[0]));
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}
